#!/bin/sh
if [ $# = 0 ]
then
  echo "Argument required: <test name>"
  exit 1
fi
echo "Running test: $1"
rm -rf ut_drive  # ut for unit test
rm -f test.cld test.err
mkdir -p ut_drive
cp -f "$1".bas ut_drive/
# National CF-3300 is chosen because it uses BASIC 1.0 and includes a floppy.
openmsx -machine National_CF-3300 -control stdio -diska ut_drive/\
 -script output_capture.tcl > /dev/null <<EOF
<openmsx-control>
<command>set save_settings_on_exit false</command>
<command>set renderer none</command>
<command>set maxframeskip 100</command>
<command>set throttle false</command>
<command>after time 30 exit</command>
<command>set power on</command>
<command>type_via_keybuf "\r\rload\"$1.bas\"\rsave\"test.cld\"\r"</command>
</openmsx-control>
EOF
python3-coverage run -a ../asc2cld.py "$1".bas test.cld 1 3>&2 2>&1 1>&3 |\
 sed -rn 's/.*BasicError: //p' > test.err
if [ ! -e "$1".out ]
then
  # Error expected.
  rm -rf ut_drive
  # Compare error message with actual error from machine.
  # Remove ESC Y sequences and CRs from input, as a normalization.
  sed -r -e $(printf 's/\eY..|\r//g') msx.out\
   | egrep -A9999 '^load"'\
   | egrep -q "$(printf "\n\a?" ; cat test.err)$(printf "\a?\n")" -\
   || { echo "Error message differs, test: $1"; exit 1; }
  rm -f test.err msx.out
  exit 0
fi

# Success expected. Normalize like above to make msx.out and $1.out comparable.
sed -r -e "$(printf 's/\eY..|\r//g')" msx.out | egrep -A9999 '^load"'\
 | cmp "$1".out - || { echo "Expected output failed, test: $1"; exit 1; }

# Compare tokenized code.
cmp test.cld ut_drive/test.cld\
 || { echo "Mismatch in tokenized code, test: $1"; exit 1; }

# Cleanup
rm -rf ut_drive
rm -f test.err msx.out test.cld
